package com.ng.config;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ng.common.redis.RedisUtils;
import com.ng.common.utils.Constant;
import com.ng.common.utils.MD5Utils;
import com.ng.sys.entity.SysUserEntity;

@Component
public class SysConfig {
	
	Logger logger = LoggerFactory.getLogger(getClass());

	
	String salt = "39efqRGvSswrDhTZTWR2";
	
	
	@Autowired
	private RedisUtils redisUtils;
	
	// 2021-05-08 superAdmin用户存入redis 防止多节点部署的时候冲突
	
	public SysConfig() {
		// TODO Auto-generated constructor stub
		
		// 尝试判断本地缓存文件中是否有密码文件
		/*File f = new File("superpass.txt");
		if(f.exists()) {
			logger.info("super admin pass exists.");
			
			try {
				String filepass = FileUtils.readFileToString(f , "UTF-8");
				if(StringUtils.isNotBlank(filepass)) {
					this.password = filepass;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}*/
		
	}
	
	public SysUserEntity getAdminUser() {
		SysUserEntity  sae = new SysUserEntity ();
		sae.setUserId(Constant.SUPER_ADMIN);
		sae.setUserNo(Constant.SUPER_ADMIN);
		//String pass = "123456";
		
		String adminPass = "" ;
		
		// 从nginx中获取密码 
		String passKey = getClass().getSimpleName() + "." + Constant.SUPER_ADMIN + ".pass" ;
		if(redisUtils.containKey(passKey)) {
			adminPass = redisUtils.get(passKey, String.class);
		} else {
			String pass = "admin";
			adminPass = MD5Utils.md5Pass(pass, salt);
			 
			redisUtils.set(passKey, adminPass, 60 * 60 * 24 * 3650);
			System.out.println("set pass , key:" + passKey);
		}
		
		
		
		sae.setPassword(adminPass);
		sae.setSalt(salt);
		sae.setStatus(1);
		sae.setUsername(Constant.SUPER_ADMIN);
		 
		return sae; 
	}
	
	
	public void updatePassword(String password) {
		
		// 修改redis内的超管密码
		  
		String passKey = getClass().getSimpleName() + "." + Constant.SUPER_ADMIN + ".pass" ;
		
		redisUtils.set(passKey, password, 60 * 60 * 24 * 3650);
		
		// 写入文件
//		File f = new File("superpass.txt");
//		try {
//			FileUtils.write(f, password , "UTF-8");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
	
	public static void main(String[] args) {
		String slat = RandomStringUtils.randomAlphanumeric(20);
		
		System.out.println(slat);
	}
	
}
